﻿using System;
using System.Collections.Generic;
using Codemonk.Common.Caching;

namespace Codemonk.Common.ObjectModel
{
    /// <summary>
    /// 事物上下文管理器
    /// </summary>
    internal static class TransactionContextManager
    {
        private static ICacheCollection<int, Stack<TransactionContext>> contextTable
            = new DictionaryCache<int, Stack<TransactionContext>>();

        internal static void Push(TransactionContext context)
        {
            if (context == null) return;
            var id = System.Threading.Thread.CurrentThread.ExecutionContext.GetHashCode();
            Stack<TransactionContext> contexts = null;
            if (contextTable.TryGet(id, out contexts)) contexts.Push(context);
            else
            {
                contexts = new Stack<TransactionContext>();
                contexts.Push(context);
                contextTable.Set(id, contexts);
            }
        }

        internal static void Pop()
        {
            var id = System.Threading.Thread.CurrentThread.ExecutionContext.GetHashCode();
            Stack<TransactionContext> contexts = null;
            if (contextTable.TryGet(id, out contexts)) contexts.Pop();
        }

        internal static TransactionContext CurrentContext
        {
            get
            {
                var id = System.Threading.Thread.CurrentThread.ExecutionContext.GetHashCode();
                Stack<TransactionContext> contexts = null;
                if (contextTable.TryGet(id, out contexts)) return contexts.Peek();
                throw new ArgumentException();
            }
        }
    }
}
